package com.fankui.serviceorder.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fankui.commonutils.JwtUtils;
import com.fankui.commonutils.R;
import com.fankui.serviceorder.entity.Order;
import com.fankui.serviceorder.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author 范奎
 * @since 2023-12-12
 */
@Api(description = "订单管理")
@RestController
@RequestMapping("/orderservice/order")
public class OrderController {
    @Autowired
    private OrderService orderService;

    @ApiOperation(value = "生成订单")
    @PostMapping("createOrder/{courseId}")
    public R saveOrder(@ApiParam(value = "courseId", name = "课程id", required = true) @PathVariable String courseId,
                       @ApiParam(value = "request", name = "request对象", required = true) HttpServletRequest request) {
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        if (StringUtils.isEmpty(memberId)) {
            return R.error().message("请登录后再进行购买！");
        }
        String orderNo = orderService.saveOrder(courseId, memberId);
        return R.ok().data("orderNo", orderNo);
    }

    @ApiOperation(value = "根据订单号查询订单信息")
    @GetMapping("getOrder/{orderNo}")
    public R getOrder(@ApiParam(value = "orderNo", name = "订单号", required = true) @PathVariable String orderNo) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no", orderNo);
        Order order = orderService.getOne(wrapper);
        return R.ok().data("order", order);
    }

    @ApiOperation(value = "根据课程id和用户id查询订单支付状态")
    @GetMapping("isBuyCourse/{courseId}/{memberId}")
    public boolean isBuyCourse(@ApiParam(value = "course", name = "课程id", required = true) @PathVariable String courseId,
                               @ApiParam(value = "memberId", name = "用户id", required = true) @PathVariable String memberId) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id", courseId);
        wrapper.eq("member_id", memberId);
        wrapper.eq("status", 1);
        int count = orderService.count(wrapper);
        if (count > 0) {
            return true;
        } else {
            return false;
        }
    }
}

